import time
from prg.common.semaphore_base import SemaphoreItem
from prg.common.object_message import MessageBase


class UdpConfirm(MessageBase):
    def __init__(self, socket_item, array_byte):
        super().__init__(name="udp_confirm")
        self.socket_item = socket_item
        self.conf_step = SemaphoreItem()
        self.conf_step.acquire()
        self.addr = None
        self.array_byte = array_byte
        self.send(2)

    def acquire(self):
        self.conf_step.acquire()

    def send(self, byte_item):
        rtn = False
        try:
            self.socket_item.send(bytes([byte_item]))
            # print("send data %d" % byte_item)
            rtn = True
        except Exception as e:
            print("send error %s" % e)
        finally:
            time.sleep(1)
        return rtn

    def recv(self, byte_item):
        rtn = False
        try:
            read_byte_tmp = self.array_byte.read(1)
            # print("recv data %d" % read_byte_tmp[0])
            if byte_item == read_byte_tmp[0]:
                rtn = True
        except Exception as e:
            print("recv error %s" % e)
        finally:
            time.sleep(1)
        return rtn

    def send_ready_run(self):
        print("wait response...")
        while True:
            if self.send(4) and self.recv(4):
                break
        print("response ready")

    def send_confirm_run(self):
        print("wait confirm...")
        while True:
            if self.send(4) and self.send(8) and self.recv(8):
                break
        print("confirm ready")

    def send_start(self):
        print("wait start...")
        self.send(255)
        while not self.recv(255):
            pass
        print("connect start")

    def run_confirm(self, addr):
        self.semaphore_item = None
        self.addr = addr
        self.start()
        self.acquire()

    def entry(self):
        self.send_ready_run()
        self.send_confirm_run()
        self.send_start()
        self.conf_step.release()

